# py3

import web
import json
import datetime
import configparser
  
class DateEncoder(json.JSONEncoder):  
    def default(self, obj):  
        if isinstance(obj, datetime.datetime):  
            return obj.strftime('%Y-%m-%d %H:%M:%S')  
        elif isinstance(obj, date):  
            return obj.strftime("%Y-%m-%d")  
        else:  
            return json.JSONEncoder.default(self, obj) 

urls = (
    '/', 'index',
    '/index-data(.*?)', 'indexData',
    '/admin', 'admin',
    '/admin-mods', 'adminMods',
    '/admin-news', 'adminNews',
    '/admin-add-news', 'adminAddNews',
    '/admin-edit-news', 'adminEditNews',
    '/admin-del-news/(.*?)', 'adminDelNews',
    '/admin-get-news/(.*?)', 'adminGetNews',
    '/admin-mods-save', 'adminModsSave',
    '/news/(.*?)', 'news',
)
app = web.application(urls, globals())
cf = configparser.ConfigParser()
cf.read('../config/env.ini')
db = web.database(
        dbn = cf.get('db', 'dbn'),
        user = cf.get('db', 'user'),
        pw = cf.get('db', 'pw'),
        db = cf.get('db', 'db'),
        )
class index:
    def GET(self):
        f = open("../tpl/index.html", "rb")
        return f.read()
class indexData:
    def GET(self, name):
        r = list(db.select("mods", where="visible=1"))
        arr = []
        for i in r:
            tmp = {"modname": i['name'], "data": list(db.select("news", where="visible=1 and mod_id=" + str(i['id'])))}
            arr += [tmp]
        out = {"errno": 0, "errmsg": "", "data": arr}
        return json.dumps(out, cls=DateEncoder)
class admin:
    def GET(self):
        f = open("../tpl/admin.html", "rb")
        return f.read()
class adminMods:
    def GET(self):
        r = list(db.select("mods"))
        out = {"errno": 0, "errmsg": "", "data": r}
        return json.dumps(out, cls=DateEncoder)
class adminNews:
    def GET(self):
        r = list(db.select("news", where="visible=1"))
        out = {"errno": 0, "errmsg": "", "data": r}
        return json.dumps(out, cls=DateEncoder)
class adminAddNews:
    def POST(self):
        data = web.data()
        data = bytes.decode(data) # bytes to string 
        r = json.loads(data)
        r1 = db.insert("news", mod_id=r['mod_id'], title=r['title'], content=r['content'])
        return r1
class adminEditNews:
    def POST(self):
        data = web.data()
        data = bytes.decode(data) # bytes to string 
        r = json.loads(data)
        r1 = db.update("news", where="id=" + r['edit_id'], mod_id=r['mod_id'], title=r['title'], content=r['content'])
        return r1
class adminModsSave:
    def POST(self):
        data = web.data()
        data = bytes.decode(data) # bytes to string 
        r = json.loads(data)
        for i in r:
            r1 = db.update("mods", where="id=" + i['id'], name=i['name'], visible=i['visible'])
        return r1

class adminGetNews:
    def GET(self, name):
        r = list(db.select("news", where="visible=1 and id=" + name, limit=1))[0]
        out = {"errno": 0, "errmsg": "", "data": r}
        return json.dumps(out, cls=DateEncoder)
class adminDelNews:
    def GET(self, name):
        return db.update("news", where="id=" + name, visible=0)
class news:
    def GET(self, name):
        f = open("../tpl/news.html", "rb")
        r = list(db.select("news", where="visible=1 and id=" + name, limit=1))[0]
        r = json.dumps(r, cls=DateEncoder)
        f = bytes.decode(f.read())
        r = "var json = " + r + ";"
        # return type(r)
        f = f.replace('var json = {};', r)
        #return json.dumps(r, cls=DateEncoder)
        return f
        return 
if __name__ == "__main__":
    app.run()
